package yonghe
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.media.Camera;
	import flash.media.Video;
	CONFIG::NOT_LINUX
	{
		import flash.events.PermissionEvent;
		import flash.permissions.PermissionStatus;
	}

	public class MyCam extends Sprite
	{
		private static var mains:MyCam;

		public static function get main():MyCam
		{
			if (mains == null)
				mains = new MyCam();
			return mains;
		}

		static public const FLV_FRAMERATE:int = 10;
		public static var video:Video = null;
		private static var camera:Camera = null;
		private var OUTPUT_WIDTH:int = 320;
		private var OUTPUT_HEIGHT:int = 240;

		public function MyCam(w:int=0,h:int=0)
		{
			if (mains)
				return;
			mains = this;
			mouseChildren = false;
		}
		public function setSize(w:int,h:int):void
		{
			if(w==OUTPUT_WIDTH && h==OUTPUT_HEIGHT)
				return;
			OUTPUT_WIDTH = w;
			OUTPUT_HEIGHT = h;
			start_photo();
		}

		private function startCam():void
		{
			if (Camera.isSupported){
				camera = Camera.getCamera();
				if (camera == null){
					logs.adds("no Camera");
					return;
				}

				CONFIG::NOT_LINUX
				{
					if (Camera.permissionStatus != PermissionStatus.GRANTED)
					{
						camera.addEventListener(PermissionEvent.PERMISSION_STATUS, permission);
						try
						{
							camera.requestPermission();
						}
						catch (e:Error)
						{
							// another request is in progress
							logs.adds(e);
						}
					}
					else
					{
						connectCamera();
					}
					return;
				}
				connectCamera();
			}
			else
			{
				logs.adds("Camera is not support");
			}
		}

		CONFIG::NOT_LINUX
		{
			private function permission(e:PermissionEvent):void
			{
				if (e.status == PermissionStatus.GRANTED)
				{
					connectCamera();
				}
				else
				{
					// permission denied
					logs.adds("permission denied");
				}
			}
		}

		private function connectCamera():void
		{
			camera.setMode(OUTPUT_WIDTH, OUTPUT_HEIGHT, FLV_FRAMERATE);
			//camera.setQuality(0, 100);

			video = new Video(OUTPUT_WIDTH, OUTPUT_HEIGHT);
			video.attachCamera(camera);
			addChild(video);
			video.visible = true;
			logs.adds("Camera started");
		}

		public function start_photo(e:Event = null):void
		{
			visible = true;
			if (video){
				video.visible = true;
				addChild(video);
				video.width = OUTPUT_WIDTH;
				video.height = OUTPUT_HEIGHT;
			}else{
				startCam();
			}
		}

	}
}

